package com.whpu.service.impl;

import com.alibaba.fastjson.JSON;
import com.whpu.mapper.UserMapper;
import com.whpu.pojo.User;
import com.whpu.service.UserService;
import com.whpu.utils.JedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAll(int pageNum, int pageSize) {
        List<User> users = new ArrayList<>();
        List<User> allByRedis = this.findAllByRedis();
        for (int i = (pageNum - 1) * pageSize; i < allByRedis.size() && i < pageNum * pageSize; i++) {
            users.add(allByRedis.get(i));
        }
        return users;
    }

    @Override
    public List<User> findAllByRedis() {
        Jedis jedis = JedisUtil.getJedis();
        String usersJSON = jedis.get("USERS");
        if (usersJSON == null || usersJSON.length() <= 0) {
            List<User> users = userMapper.findAll();
            usersJSON = JSON.toJSONString(users); //转化成字符串
            jedis.set("USERS", usersJSON);
        }
        List<User> list = JSON.parseArray(usersJSON, User.class);
        //关闭jedis
        JedisUtil.close(jedis);
        return list;
    }

    @Override
    public void save(User user) {
        System.out.println("service-->save");
        userMapper.save(user);
        //删除redis的users集合
        Jedis jedis = JedisUtil.getJedis();
        jedis.del("USERS");
    }
}
